<?php

namespace App\Logics;


use App\Models\CourseStudent;
use App\Models\Event;
use App\Models\Order;
use App\Models\OrderUser;
use App\Models\Student;
use App\Models\User;
use App\Service\Base\Logic;
use function Symfony\Component\Translation\t;

class OrderLogic extends Logic
{

    // 订单


    // 增加订单学员
    //   学校最多10个学员
    //   学员+机构：只能给自己报名


    // 退款
    public function onRefund($myUid)
    {
        $opt      = $this->option();
        $order_id = $opt->getData('order_id', 0, 'intval');
        $user_ids = $opt->getData('user_ids', [], 'is_array');  // 退款订单用户ID
        $money    = $opt->getData('money', 0, 'floatval');
        if(empty($order_id)){
            return $this->_returnFail('请传递退款订单编号！');
        }
        if(empty($user_ids)){
            return $this->_returnFail('请传递退款报名用户！');
        }
        if(empty($money)){
            return $this->_returnFail('请传递支付金额！');
        }

        // 执行下单
        $orderDb = new Order();
        $result  = $orderDb->refundOrder($myUid, $order_id, $user_ids);
        if($result === false){
            return $this->_returnFail($orderDb->getError());
        }

        return $result;
    }

    // 下单操作
    public function makeOrder($myUid)
    {
        $opt       = $this->option();
        $event_id  = $opt->getData('event_id', 0, 'intval');
        $share_uid = $opt->getData('share_uid', 0, 'intval');
        $users     = $opt->getData('users', [], 'is_array');  // 报名用户列表
        $money     = $opt->getData('money', 0, 'floatval');

        // TODO $users 用户字段整理
        //   可能是选择的学员   person_name   age   sex   mobile  guardor
        //   可能自己的认证的   student_id 可以是 [1,2,3] 或者 [{student_id:1},{student_id:2},]

        // 没有认证的用户 只能为自己报名
        // 认证的用户 最多只能为10个人报名
        // $allUsers = $this->checkOrderUser($user, $users);

        // 执行下单
        $orderDb = new Order();
        $result  = $orderDb->makeOrder($myUid, $event_id, $users, $share_uid, $money);
        if($result === false){
            return $this->_returnFail($orderDb->getError());
        }

        return $result;
    }

    // 订单用户：
    //  某个订单，最新的订单用户
    //  某个活动，最新的订单用户
    public function getStudent($page = 0, $rows = 0)
    {
        $option = $this->option();
        $page   = $page ?: $option->getData('page', 0, 'intval');
        $rows   = $rows ?: $option->getData('rows', 15, 'intval');
        $start  = $page ? ($page - 1) * $rows : 0;

        // 模型 和 查询
        $where   = [];
        $bang    = [];
        $is_even = $option->getData('add_event', 0, 'intval');  // 添加活动信息
        $o_id    = $option->getData('order_id', 0, 'intval');
        $e_id    = $option->getData('event_id', 0, 'intval');
        $s_id    = $option->getData('student_id', 0, 'intval');
        $o_uid   = $option->getData('order_uid', 0, 'intval');
        $name    = $option->getData('name', null, 'trim');
        $keyword = $option->getData('keyword', null, 'trim');
        if($o_id){
            $bang[]  = 'order_id';
            $where[] = ['order_id', '=', $o_id];
        }
        if($e_id){
            $bang[]  = 'event_id';
            $where[] = ['event_id', '=', $e_id];
        }
        if($s_id){
            $bang[]  = 'student_id';
            $where[] = ['student_id', '=', $s_id];
        }
        if($o_uid){
            $bang[]  = 'order_uid';
            $where[] = ['order_uid', '=', $o_uid];
        }
        if($name){
            $bang    = false;
            $where[] = ['name', 'like', "%".$name."%"];
        }

        // 模型
        /*$KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        if(empty($lists)){}*/
        $model = new OrderUser();
        if($page){
            $result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            // 增加活动信息
            if($is_even){
                $result['list'] = $this->listsAddEvent($result['list']);
            }
        } else{
            $result = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
            // 增加活动信息
            if($is_even){
                $result = $this->listsAddEvent($result);
            }
        }

        return $result;
    }

    // 获取订单
    public function getOrder()
    {
        $option  = $this->option();
        $status  = $option->getData('status', null, 'intval');
        $_refund = $option->getData('is_refund', null, 'intval');
        $page    = $option->getData('page', 1, 'intval');
        $rows    = $option->getData('rows', 15, 'intval');
        $e_id    = $option->getData('event_id', 0, 'intval');
        $uid     = $option->getData('order_uid', 0, 'intval');

        // 模型 和 查询
        $where = [];
        $bang  = [];
        if($e_id){
            $bang[]  = 'event_id';
            $where[] = ['event_id', '=', $e_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['uid', '=', $uid];
        }
        if(!is_null($status)){
            $bang[]  = 'status';
            $where[] = ['status', '=', $status];
        }
        if(!is_null($_refund)){
            $bang[]  = 'is_refund';
            $where[] = ['is_refund', '=', $_refund];
        }

        // 模型
        /*$KCache = $model->cacheKey('lists', $where);
        $lists  = $model->cacheClass()->getCache($KCache);
        if(empty($lists)){}*/
        $model = new Order();
        if($page){
            $result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            // 订单活动信息
            $result['list'] = $this->getOrderAttr($result['list']);
        } else{
            $start  = $page ? ($page - 1) * $rows : 0;
            $result = $model->bangField($bang)->getList($where, $rows, "id DESC", $start);
            // 订单活动信息
            $result = $this->getOrderAttr($result);
        }

        return $result;
    }

    // 订单详情
    public function onShow()
    {
        $option = $this->option();
        $_id    = $option->getData('id', null, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定查看订单的编号！');
        }

        // 模型
        $model = new Order();
        $info  = $model->isCache(true)->oneFind(['id' => $_id]);
        if(empty($info)){
            return $this->_returnFail('指定查看订单不存在！');
        }

        // 属性
        $info['event'] = (new Event())->isCache(true)->oneFind(['id' => $info['event_id']]);
        $info['users'] = (new OrderUser())->isCache(true)->getList(['order_id' => $info['id']]);

        return $info;
    }


    // 随机用户头像
    protected function randHeadImg($url = '')
    {
        if($url){
            return $url;
        }

        // 从数组中随机获取
        // $imgs = [];
        // $_key = array_rand($imgs);
        // $img  = $imgs[$_key];

        // 从七牛云中获取
        // 纯色头像：已经删除 'https://img.shenlanhui.com/static/sys_head_img/face_'.rand(1, 75).'.jpg';
        // 一般头像 'https://img.shenlanhui.com/static/head_img/face_'.rand(1, 450).'.jpg';
        $img = 'https://img.shenlanhui.com/static/head_img/face_'.rand(1, 450).'.jpg';

        return $img;
    }

    // 检查报名用户信息
    // 没有认证的用户 只能为自己报名
    // 认证的用户 最多只能为10个人报名
    protected function checkOrderUser($myUser, $users)
    {
        $number = count($users);
        if(empty($is_auth)){
            /*if($number > 1){
                return $this->_returnFail('你只能为自己报名！');
            }*/

            $users['head_img']  = $this->randHeadImg($myUser['head_img']);  // 头像
            $users['order_uid'] = $myUser['id'];  // 头像
            if(empty($users['person_name']) || empty($users['age']) || empty($users['sex']) || empty($users['mobile']) || empty($users['guardor'])){
                return $this->_returnFail('传递的用户数据确实必要信息！');
            }

            // 重新组合
            $allUsers = [$users];
        } else{
            if($number > 10){
                return $this->_returnFail('你最多一次性只能为10个人报名！');
            }

            // 学员id
            $sIds = array_column($users, 'student_id');
            $sIds = $sIds ?: $users;
            // 查询学员信息
            $stds = (new Student())->isCache(true)->getListInIds($sIds);
            // 整理 报名学员信息
            $allUsers = [];
            foreach($stds as $_stu){
                $allUsers[] = [
                    'student_id'  => $_stu['id'],
                    'order_uid'   => $_stu['uid'],
                    'person_name' => $_stu['person_name'],
                    'head_img'    => $this->randHeadImg($_stu['head_img']),
                    'sex'         => $_stu['sex'],
                    'age'         => $_stu['age'],
                    'guardor'     => $_stu['guardor'],
                    'mobile'      => $_stu['mobile'],
                ];
            }
        }

        return $allUsers;
    }

    // 订单的活动信息
    protected function getOrderAttr($lists)
    {
        if(empty($lists)){
            return $lists;
        }

        // 获取活动信息
        $eids   = array_column($lists, 'event_id');
        $events = (new Event())->isCache(true)->getListInIds($eids);
        foreach($lists as $key => $item){
            $lists[$key]['event'] = $events[$item['event_id']] ?? [];
            //$lists[$key]['users'] = (new OrderUser())->isCache(true)->getList(['order_id' => $item['id']]);
        }

        return $lists;
    }

}


